<template>
  <div class="category-container">
    <div class="bg-linear"
      id="linear">
      <div class="max-w-11xl mx-auto px-4 py-10 lg:flex lg:items-center">
        <div class="lg:flex-1">
          <h1 class="text-40 text-gray-1000 break-words font-semibold"
            v-html="$t('category_findAIByCategories')"></h1>
          <p class="text-lg text-gray-1000 mt-3">
            {{$t('category_overCategoriesToFindAI',{categoriesNum: category_count})}}
          </p>
        </div>
        <div class="mt-4 lg:block lg:mt-0 lg:flex-shrink-0 lg:ml-3">
          <top-advertiser></top-advertiser>
        </div>
      </div>
    </div>

    <div class="max-w-11xl mx-auto px-4 py-8">
      <div class="lg:flex items-start gap-5">
        <div class="sideBar-box overflow-y-auto lg:sticky lg:top-24 flex-shrink-0 lg:w-52 max-w-full flex flex-wrap gap-y-1 gap-x-4 lg:space-y-1 lg:block">
          <!-- <div class="category-item"
            key="group-all">
            <span class="inline-flex text-md py-2 px-3 rounded-md text-gray-1500">
              {{$t('category_all')}}
            </span>
          </div> -->
          <template v-for="(item, key) in groupsList">
            <div class="category-item"
              :key="`menu-${item.name}-${key}`">
              <span class="inline-flex cursor-pointer text-base py-2 px-3 rounded-md"
                :class="{'text-purple-1300 bg-purple-1300 bg-opacity-10 font-semibold hover:opacity-90': activeName === `group-${item.handle}`, 'text-gray-1000 hover:text-purple-1300': activeName !== `group-${item.handle}`}"
                @click="toHref(`#group-${item.handle}`)">
                {{item.name}}
              </span>
            </div>
          </template>
        </div>

        <div class="flex-1 mt-5 lg:mt-0 lg:w-0 bg-white rounded-md">
          <!-- <h3 class="text-26 leading-normal text-purple-1300 font-semibold break-words mb-4"
            id="group-all"
            v-if="recommendTopList && recommendTopList.length > 0">{{$t('category_featured')}}</h3>
          <div class="tools grid gap-5 sm:grid-cols-3 md:grid-cols-3 lg:grid-cols-3 xl:grid-cols-4 mb-5"
            v-if="recommendTopList && recommendTopList.length > 0">
            <min-tool v-for="(item, key) in recommendTopList"
              :key="item.handle+'-'+key"
              :toolPosIndex="key"
              toolPosition="Top"
              :toolsData="item"></min-tool>
          </div> -->
          <h3 class="text-26 leading-normal text-purple-1300 font-semibold break-words mb-4"
            id="group-all"
            v-if="recommendTopList && recommendTopList.length > 0">{{$t('category_featured')}}</h3>
          <div class="tools grid gap-5 sm:grid-cols-3 md:grid-cols-3 lg:grid-cols-3 xl:grid-cols-4 mb-5"
            :key="`${$route.name}-Featured`"
            v-if="recommendTopList && recommendTopList.length > 0">
            <min-tool v-for="(item, key) in recommendTopList"
              :key="`${item.handle}-${key}-${$route.name}-Featured`"
              :toolPosIndex="key"
              toolPosition="Featured"
              :toolsData="item"
              :lazyLoad="false"></min-tool>
          </div>
          <div class="list space-y-6">
            <template v-for="(item, key) in groupsList">
              <div :key="`category-${key}`"
                :id="`group-${item.handle}`">
                <h3 class="text-26 leading-normal text-gray-1000 font-semibold break-words">{{item.name}}</h3>
                <div class="mt-4 grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4"
                  v-if="item.values && item.values.length>0">
                  <common-link path="/category/:handle"
                    :params="{ handle:cItem.handle }"
                    v-for="(cItem, cKey) in item.values"
                    :key="cItem.handle"
                    class="border rounded border-gray-1600 flex items-center justify-between h-11 px-4 text-gray-1000 hover:bg-purple-1000 hover:border-purple-1000 go-category-link">
                    <span class="text-base text-gray-1000 flex-1 w-0 truncate font-medium">
                      {{cItem.name}}
                    </span>
                    <div class="whitespace-nowrap flex-shrink-0 text-base text-purple-1300 font-medium">
                      {{cItem.tool_count}}
                    </div>
                  </common-link>
                </div>
                <el-empty v-else
                  :description="$t('category_noData')"></el-empty>
              </div>
            </template>
          </div>
          <h3 class="text-26 leading-normal text-purple-1300 font-semibold break-words mb-4 mt-6"
            id="group-all"
            v-if="recommendBottomList && recommendBottomList.length > 0">{{$t('recommend_moreRecommend')}}</h3>
          <div class="tools grid gap-5 sm:grid-cols-3 md:grid-cols-3 lg:grid-cols-3 xl:grid-cols-4 mb-5"
            v-if="recommendBottomList && recommendBottomList.length > 0"
            :key="`${$route.name}-bottom`">
            <min-tool v-for="(item, key) in recommendBottomList"
              :key="`${item.handle}-${key}-${$route.name}-bottom`"
              :toolPosIndex="key"
              toolPosition="Bottom"
              :toolsData="item"></min-tool>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  name: 'GroupPage',
  head() {
    return {
      htmlAttrs: {
        lang: this.locale,
      },
      title: this.title,
      meta: [
        {
          hid: 'description',
          name: 'description',
          content: 'Find all the best AI tools on the market by category.',
        },
        {
          hid: 'og:title',
          name: 'og:title',
          content: this.title,
        },
        {
          hid: 'og:description',
          name: 'og:description',
          content: 'Find all the best AI tools on the market by category.',
        },
        {
          hid: 'og:url',
          name: 'og:url',
          content: this.canonicalLink,
        },
        {
          hid: 'og:image:alt',
          name: 'og:image:alt',
          content: this.title,
        },
      ],
      link: [
        {
          rel: 'canonical',
          href: this.canonicalLink,
        },
      ],
    }
  },
  async asyncData({ app, route, params, query, $axiosApi, error, store }) {
    try {
      let [categoriesRes, recommendRes] = await Promise.all([
        $axiosApi.getCategoriesGroups({
          order_by: 'created_at',
        }),
        $axiosApi.searchGetAd({
          limit: 9,
        }),
        /* $axiosApi.getTools({
          order_by: 'recommended_at',
          page: 1,
          per_page: 100,
          only_recommend: 1,
        }), */
      ])

      let groupsList,
        allCategory,
        domArr = ['group-all'],
        category_count = 0
      if (categoriesRes.code === 200) {
        groupsList =
          categoriesRes.data.groups && categoriesRes.data.groups.length > 0
            ? categoriesRes.data.groups
            : []

        groupsList.forEach((item, key) => {
          domArr.push(`group-${item.handle}`)
        })

        allCategory =
          categoriesRes.data.all_category &&
          categoriesRes.data.all_category.length > 0
            ? categoriesRes.data.all_category
            : []

        category_count = categoriesRes.data.category_count

        //就近取整百、整千
        /* if (category_count && category_count > 100) {
          let numStr = String(parseInt(category_count))
          const len = numStr.length
          const arr = numStr.split('')
          for (let i = 0; i < len; i++) {
            arr[i] = i < len - 2 ? arr[i] : '0'
          }
          category_count = `${arr.join('')}+`
        } else {
          category_count = category_count
        } */
      } else {
        if (categoriesRes && categoriesRes.code && categoriesRes.code === 404) {
          error({ statusCode: 404 })
        } else if (
          !(categoriesRes && categoriesRes.code && categoriesRes.code === 401)
        ) {
          error({
            message:
              'There is a problem with the network. Please refresh and try again later',
            statusCode: categoriesRes.code,
          })
        }
      }

      let recommendTopList = []
      let recommendBottomList = []
      if (
        recommendRes.code === 200 &&
        recommendRes.data &&
        recommendRes.data.featured_list &&
        recommendRes.data.featured_list.length > 0
      ) {
        store.commit(
          'SET_TOP_ADVERTISER',
          JSON.parse(JSON.stringify(recommendRes.data.featured_list[0]))
        )
        recommendTopList = recommendRes.data.featured_list.slice(1, 5)
        recommendBottomList = recommendRes.data.featured_list.slice(5, 9)
      } else {
        store.commit('SET_TOP_ADVERTISER', null)
      }

      /* if (toolsRes.code === 200) {
        recommendTopList =
          toolsRes.data.data && toolsRes.data.data.length > 0
            ? toolsRes.data.data
            : []
      } */

      let title = app.i18n.t('categoriesSEOTitle')

      return {
        groupsList,
        allCategory,
        title,
        domArr,
        category_count,
        recommendTopList,
        recommendBottomList,
      }
    } catch (err) {
      console.log(err)
    }
  },
  computed: {
    ...mapState({
      locale: (state) => state.locale,
      top_advertiser: (state) => state.locale,
    }),
  },
  watch: {
    $route: {
      handler() {
        this.$nextTick(() => {
          if (this.$route.query.group && process.browser) {
            this.toHref(`#group-${this.$route.query.group}`)
          } else {
            this.activeName = 'group-all'
          }
        })
      },
      immediate: true,
      deep: true,
    },
  },
  data() {
    return {
      canonicalLink: `https://www.toolify.ai${this.$route.fullPath}`,
      recommendTopList: [],
      recommendBottomList: [],
      groupsList: [],
      title: null,
      allCategory: [],
      domArr: [],

      activeName: null,
      isScrolling: false,
      timer: null,
      scrollTop: 0,
      category_count: 0,
    }
  },
  mounted() {
    window.addEventListener('scroll', this.onSroll)
    this.setMaxHeight()
  },
  methods: {
    setMaxHeight() {
      //变量windowHeight是可视区的高度
      var windowHeight =
        document.documentElement.clientHeight || document.body.clientHeight
      //变量windowHeight是可视区的高度
      var windowWidth =
        document.documentElement.clientWidth || document.body.clientWidth
      let sideBarDom = document.querySelector('.sideBar-box') // 通过id获取div元素
      const distanceToTop = sideBarDom.getBoundingClientRect().top
      let maxHeight = windowHeight - distanceToTop - 20

      if (maxHeight > 400 && windowWidth >= 1024) {
        sideBarDom.style.maxHeight = `${maxHeight}px`
      } else if (windowWidth >= 1024) {
        sideBarDom.style.maxHeight = `none`
      } else {
        sideBarDom.style.maxHeight = '400px'
      }
    },
    getLocaleText(val, val_locales) {
      if (
        Object.prototype.toString.call(val_locales) === '[object Object]' &&
        typeof val_locales[this.locale] != 'undefined' &&
        val_locales[this.locale] !== null &&
        val_locales[this.locale] !== ''
      ) {
        return val_locales[this.locale]
      } else {
        return val
      }
    },
    toHref(val) {
      const dom = document.querySelector(val)
      if (dom) {
        window.removeEventListener('scroll', this.onSroll)
        this.activeName = val.replace('#', '')

        this.$router.replace({
          query: { group: this.activeName.replace('group-', '') },
        })

        this.isScrolling = true
        const top = dom.offsetTop

        const targetScrollPosition = Math.max(top - 100, 0)

        window.scrollTo({
          top: targetScrollPosition,
          behavior: 'auto',
        })

        let timer = setTimeout(() => {
          this.$nextTick(() => {
            window.addEventListener('scroll', this.onSroll)
            this.isScrolling = false

            this.setMaxHeight()
            clearTimeout(timer)
          })
        }, 300)
      }
    },
    //滚动页面跟踪导航高亮
    onSroll() {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(this.isScrollEnd, 300)
      this.scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop

      if (this.isScrolling) {
        return false
      }

      let currentDom = ''

      this.domArr.forEach((item, key) => {
        if (document.getElementById(item)) {
          let itemTop = document.getElementById(item).offsetTop

          if (this.scrollTop >= itemTop - 100) {
            currentDom = item
          }
        }
      })

      this.activeName = currentDom ? currentDom : 'group-all'

      if (this.activeName === 'group-all') {
        this.$router.replace({
          query: {},
        })
      } else {
        this.$router.replace({
          query: { group: this.activeName.replace('group-', '') },
        })
      }
      this.setMaxHeight()
    },
    //判断滚动条是否滚动结束
    isScrollEnd() {
      let scrollTopNew =
        document.documentElement.scrollTop || document.body.scrollTop
      if (this.scrollTop === scrollTopNew) {
        this.isScrolling = false
      }
    },
  },
  beforeDestroy() {
    if (this.timer) {
      clearTimeout(this.timer)
    }
    window.removeEventListener('scroll', this.onSroll)
  },
}
</script>

<style lang='scss' scoped>
.category-container {
  /*  .sideBar-box {
    max-height: 400px;
  } */
  ::v-deep .tool-item {
    .tool-desc {
      -webkit-line-clamp: 2;
    }
  }
}
</style>
